﻿using System;
using System.Collections.Generic;
using TwlPhy;

public class PhyRunState : BaseState
{
    private pb.SyncPlayerPosResp msg;
    private Vector2 dir = Vector2.zero;
    private Vector2 target = Vector2.zero;

    public override void onEnter(FSMArgs args = null)
    {
        if (args == null) return;
        this.Agent.playAnim("run", true);
        msg = (pb.SyncPlayerPosResp)args.data;
        updateArgs(msg);
    }

    public override void onRefresh(FSMArgs args = null)
    {
        if (args == null) return;
        msg = (pb.SyncPlayerPosResp)args.data;
        updateArgs(msg);
    }

    private void updateArgs(pb.SyncPlayerPosResp msg)
    {
        if (msg == null) return;
        Agent.speed = msg.speed * 0.001f;
        dir = new Vector2(msg.dir.x * 0.001f, msg.dir.y * 0.001f);
        target = new Vector2(msg.pos.x * 0.001f, msg.pos.y * 0.001f);
        //预测点
        if (msg.isKnock == 1)
        {
            float add = (long)(TimerUtils.getMillTimer() - msg.utcTime) * 0.001f;
            target.x += msg.dir.x * 0.001f * msg.speed * 0.001f * Physics2D.logicFrame * add;//当前x+延迟x
            target.y += msg.dir.y * 0.001f * msg.speed * 0.001f * Physics2D.logicFrame * add;
        }
        //Logger.log(string.Format("target x:{0} y:{1}", target.x, target.y));
        if (msg.isKnock == 2)
        {
            transToIdle();
            return;
        }
    }

    // 0.9  2  = 1.1   1 = 0.9  <= 2
    //-1.1 -2 = -0.9 -1 *dir.x 0.9 1 0.9
    // x = (target.x-box.x)*dir.x lerp.x
    public override void onTick()
    {
        Vector2 lerpPos = dir * Agent.speed * Physics2D.logicFrame;
        float x = (target.x - Agent.DyBox.centerX) * dir.x;
        float y = (target.y - Agent.DyBox.centerY) * dir.y;
        Agent.moveVec.x = x > lerpPos.x * dir.x ? lerpPos.x : x * dir.x;
        Agent.moveVec.y = y > lerpPos.y * dir.y ? lerpPos.y : y * dir.y;
        if (dir.x != 0)
        {
            if (dir.x > 0)
            {
                Agent.changeLookFlag(LookFlag.Right);
            }
            else if (dir.x < 0) {
                Agent.changeLookFlag(LookFlag.Left);
            }            
        }
        Agent.doMove(Agent.moveVec);
        //渲染
        Agent.updateRenderOrder();
    }

    private void transToIdle()
    {
        this.Agent.kickMove(target);
        this.Agent.transFsm(FSM_Flag.Idle, null, true);
    }

    public override bool allow(FSM_Flag flag)
    {
        return flag != this.Flag;
    }

}

